import { fromArrayBuffer, type GeoTIFFImage } from 'geotiff';
import { transformExtent } from 'ol/proj'
import Projection from 'ol/proj/Projection'

// 解析tif
export const parseTiff = (file: File) => {
  return new Promise<GeoTIFFImage>((resolve, reject) => {
    const reader = new FileReader();
    reader.onload = (e: ProgressEvent<FileReader>) => {
      const data = e.target?.result as ArrayBuffer
      fromArrayBuffer(data).then((tiff) => {
        resolve(tiff.getImage())
      }).catch((error) => {
        reject(error)
      })
    }
    reader.readAsArrayBuffer(file);
  })
}

// 读取geotiff
// 生成img图层
export const generateImgLayer = async (image: GeoTIFFImage) => {
  // 获取投影信息
  const geoKeys = await image.getGeoKeys()
  const projectionStr = geoKeys.ProjectedCSTypeGeoKey || geoKeys.GeographicTypeGeoKey

  const projection = new Projection({
    code: projectionStr
  })
  const width = image.getWidth()
  const height = image.getHeight()
  const [minX, minY, maxX, maxY] = image.getBoundingBox()
  const extent = transformExtent([minX, minY, maxX, maxY], projection, new Projection({
    code: 'EPSG:4326'
  }))
  return {
    imageExtent: extent,
    imageSize: [width, height],
    projection: 'EPSG:4326'
  }
}
